package com.cloud.form.common.utils;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class ImageHelper {

	/**
	 * 图片白色背景为透明
	 * 
	 * @param in
	 * @return
	 */
	public static OutputStream white2Transparent(InputStream in) {
		try {
			BufferedImage bi = ImageIO.read(in);
			ImageIcon imageIcon = new ImageIcon(bi);
			BufferedImage bufferedImage = new BufferedImage(imageIcon.getIconWidth(), imageIcon.getIconHeight(),
					BufferedImage.TYPE_4BYTE_ABGR);
			Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
			g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver());
			int alpha = 0;
			for (int j1 = bufferedImage.getMinY(); j1 <= bufferedImage.getHeight(); j1++) {
				for (int j2 = bufferedImage.getMinX(); j2 <= bufferedImage.getWidth(); j2++) {
					int rgb = bufferedImage.getRGB(j2, j1);

					int R = (rgb & 0xff0000) >> 16;
					int G = (rgb & 0xff00) >> 8;
					int B = (rgb & 0xff);
					if (((255 - R) < 30) && (255 - G) < 30 && (255 - B) < 30) {
						rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff);
					}
					bufferedImage.setRGB(j2, j1, rgb);
				}
			}
			g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());
			OutputStream out = new ByteArrayOutputStream();
			ImageIO.write(bufferedImage, "png", out);
			return out;
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if (null != in) {
					in.close();
					in = null;
				}
			} catch (Exception e2) {
			}
		}
	}

	/**
	 * 图片裁剪
	 * 
	 * @param in
	 * @return
	 */
	public static OutputStream cutImage(InputStream in, int x, int y, int width, int height) {
		try {
			BufferedImage bi = ImageIO.read(in).getSubimage(x, y, width, height);
			OutputStream out = new ByteArrayOutputStream();
			ImageIO.write(bi, "jpg", out);
			return out;
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if (null != in) {
					in.close();
					in = null;
				}
			} catch (Exception e2) {
			}
		}
	}
}
